import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";
import router from "@/router";
import { logout as logoutApi } from "@/api/auth";
import { getUserInfo } from "@/api/user";
import type { LoginResult } from "@/types/auth";
import type { UserInfo, MenuItem } from "@/types/user";

export const useUserStore = defineStore("user", () => {
  const token = ref(localStorage.getItem("token") || "");
  const userInfo = ref<UserInfo | null>(
    JSON.parse(localStorage.getItem("userInfo") || "null")
  );
  const menuList = ref<MenuItem[]>(
    JSON.parse(localStorage.getItem("menuList") || "[]")
  );

  const setToken = (newToken: string) => {
    token.value = newToken;
    localStorage.setItem("token", newToken);
  };

  const clearToken = () => {
    token.value = "";
    localStorage.removeItem("token");
  };

  // 获取用户信息和菜单
  const getInfo = async () => {
    try {
      const res = await getUserInfo();
      console.log("res", res);
      if (res.code === 200) {
        userInfo.value = res.data;
        menuList.value = res.data.resList;
        // 持久化存储用户信息和菜单
        localStorage.setItem("userInfo", JSON.stringify(res.data));
        localStorage.setItem("menuList", JSON.stringify(res.data.resList));
        return true;
      }
      return false;
    } catch (error) {
      console.error("获取用户信息失败:", error);
      return false;
    }
  };

  // 清除所有存储的信息
  const clearAll = () => {
    clearToken();
    localStorage.removeItem("username");
    localStorage.removeItem("password");
    localStorage.removeItem("userInfo");
    localStorage.removeItem("menuList");
    userInfo.value = null;
    menuList.value = [];
    // 清除动态路由
    router.getRoutes().forEach((route) => {
      if (route.name && route.name !== "login") {
        router.removeRoute(route.name);
      }
    });
  };

  // 登录
  const login = async (loginData: any) => {
    try {
      // 这里调用登录接口
      const res = { token: "mock-token" }; // 模拟接口返回
      setToken(res.token);
      return true;
    } catch (error) {
      return false;
    }
  };

  // 退出登录
  const logout = async () => {
    try {
      const res = (await logoutApi()) as LoginResult;
      if (res.code === 200) {
        clearAll();
        router.push("/login");
        ElMessage.success(res.data || "退出成功");
        return true;
      } else {
        ElMessage.error(res.msg || "退出失败");
        return false;
      }
    } catch (error: any) {
      ElMessage.error(error.message || "退出失败");
      return false;
    }
  };

  const setPath = (arr) => {
    return arr.map((a) => {
      a.resComponent = a.resComponent || a.resUrl
      if (a.resComponent && a.resType === "1") {
        a.resComponent = a.resComponent.toLowerCase().replace("_", "-");
        const sp = a.resComponent.split("/");
        a.resPath = sp[sp.length - 1];
      }
      if (a.children) {
        a.children = setPath(a.children);
      }
      return a;
    });
  };

  const menuFinalList = computed(() => setPath(menuList.value));
  console.log(menuFinalList);
  

  return {
    token,
    userInfo,
    menuList,
    menuFinalList,
    setToken,
    clearToken,
    clearAll,
    getInfo,
    login,
    logout,
  };
});
